from appengine_django.models import BaseModel
from google.appengine.ext import db
import copy
import logging

# Create your models here.
class Profile(BaseModel):
    name = db.StringProperty(required=True)
    
    @staticmethod
    def start_values():
        p = Profile.all().fetch(3)
        if len(p) != 3:
            items = ['ADMIN', 'AUTHOR', 'EDITOR']
            for item in items:
                profile = Profile(name = item)
                profile.put()

class User(BaseModel):
    name = db.StringProperty(required=True)
    email = db.StringProperty(required=True)
    profile = db.ReferenceProperty(Profile)
    
    __profile_map__ = { 'ADMIN' : 1, 'AUTHOR': 2, 'EDITOR': 3 }
    
    @staticmethod
    def get_by_id(id):
        return User.get(db.Key.from_path('User',id))
    
    @staticmethod
    def get_by_email(email):
        u = User.gql('WHERE email=:1', email).get()
        return u
        
    @staticmethod
    def get_profile_by_email(email):
        u = User.get_by_email(email)
        
        if u:
            return {'name': u.profile.name, 'id': User.__profile_map__[u.profile.name]}
        else:
            return {'name': 'NOT_LOGGED', 'id': -1}
        
    @staticmethod
    def get_admins():
        profile = Profile.gql('WHERE name=:1','ADMIN').get()
        return User.gql('WHERE profile=:1',profile)
            
class Archive(BaseModel):
    path = db.StringProperty()
    title = db.StringProperty(required=True, indexed=False)
    keywords = db.StringProperty(required=True)
    description = db.StringProperty(required=True)
    body = db.TextProperty(required=True)
    published = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
class Category(Archive):
    def id(self):
        return self.key().id()

class Post(Archive):
    categories = db.ListProperty(db.Key)
    readable_categories = db.StringProperty(required=False)
    user_author = db.ReferenceProperty(User, required=False)
    
    model = None
    
    def __init__(self, *args, **kargs):
        super(Post, self).__init__(*args, **kargs)
        self.model = Post
    
    @staticmethod
    def get_all():
        return [p for p in Post.objects.all()]
    
    def get_categories(self):
        return Category.get(self.categories)
        
    @staticmethod
    def get_by_id(id):
        return Post.get(db.Key.from_path('Post',id))